package com.sykj.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sykj.bean.bis.BisCustomUser;
import com.sykj.service.BisCustomUserService;
import com.sykj.util.AuthUtil;
import com.sykj.util.redis.RedisUtil;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: BeautyClub
 * @description: 微信登录接口
 * @author: qiaoli
 * @create: 2020-07-24 15:28
 */
@CrossOrigin
@Controller
@RequestMapping("/wx")
public class WXLoginController {
    private static final Logger logger = LoggerFactory.getLogger(WXLoginController.class);

    @Autowired
    private HttpServletRequest request;
@Autowired
    BisCustomUserService bisCustomUserService;

      /**
       * 功能描述: 公众号微信登录授权
       * @Param: []
       * @Return: java.lang.String
       * @Author: Feiwo Sicun
       * @Date: 2020/7/24 15:36
       */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin()  {
        // 这个url的域名必须要进行再公众号中进行注册验证，这个地址是成功后的回调地址
        String backUrl = "http://127.0.0.1:8087/wx/callBack";
        // 第一步：用户同意授权，获取code
        String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID + "&redirect_uri="
                + URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";

        logger.info("获取code, getCodeUrl=" + getCodeUrl);
        // response.sendRedirect(url);
        return "redirect:" + getCodeUrl;// 必须重定向，否则不能成功
    }

    
    /**
     * 功能描述: 公众号微信登录授权回调函数
     * @Param: []
     * @Return: java.lang.String
     * @Author: Feiwo Sicun
     * @Date: 2020/7/24 15:37
     */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public String callBack() throws ServletException, IOException {

        String code = request.getParameter("code");
        // 第二步：通过code换取网页授权access_token
        String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID + "&secret="
                + AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        logger.info("获取token,getTokenUrl=" + getTokenUrl);
        JSONObject getTokenJson = AuthUtil.doGetJson(getTokenUrl);
        /*
         * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
         * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
         */
        logger.info("获取token,getTokenJson=" + getTokenJson.toJSONString());

        String openid = getTokenJson.getString("openid");
        String access_token = getTokenJson.getString("access_token");
        String refresh_token = getTokenJson.getString("refresh_token");

        // 第五步验证access_token是否失效；展示都不需要
        String vlidTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        logger.info("验证token,vlidTokenUrl=" + vlidTokenUrl);
        JSONObject validTokenJson = AuthUtil.doGetJson(vlidTokenUrl);
        logger.info("验证token,validTokenJson=" + validTokenJson.toJSONString());
        if (!"0".equals(validTokenJson.getString("errcode"))) {
            // 第三步：刷新access_token（如果需要）-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki，
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid
                    + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            logger.info("刷新token,refreshTokenUrl=" + refreshTokenUrl);
            JSONObject refreshTokenJson = AuthUtil.doGetJson(refreshTokenUrl);
            /*
             * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
             * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
             */
            logger.info("刷新token,refreshTokenJson=" + refreshTokenJson.toJSONString());
            access_token = refreshTokenJson.getString("access_token");
        }

        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                + "&lang=zh_CN";
        logger.info("获取用户信息，getUserInfoUrl=" + getUserInfoUrl.toString());
        JSONObject getUserInfoJson = AuthUtil.doGetJson(getUserInfoUrl);
        /*
         * { "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE"
         * "city":"CITY", "country":"COUNTRY", "headimgurl":
         * "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
         * "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid":
         * "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
         */
        logger.info("获取用户信息，getUserInfoJson=" + getUserInfoJson.toString());

// 判断此微信号是否登录过

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("openid",getUserInfoJson.get("openid"));
        BisCustomUser bis=bisCustomUserService.getOne(queryWrapper);
        //       将微信中的信息添加到Redis中
        if(bis==null){
            //生成一个时间加随机数的串
//            int codess=(int)((Math.random()*9+1)*1000);
//            Date date = new Date();
//            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
//            String stata=dateFormat.format(date)+codess;
            //将微信信息存到redis中
            String openid1 = (String) getUserInfoJson.get("openid");
            RedisUtil.set(openid1,getUserInfoJson,60*10);
            return "redirect:http://127.0.0.1:8080/tabbar/"+openid1;
        }
 /**
  * 功能描述: 前台登录微信时，在回调时 判断是否是第一次登录，若为第一次则将信息存入redis 并返回其reids键，
  * 若不是第一次登录，就在数据库查询，将查询到的id返回到前端
  */


        String openid1 = (String) getUserInfoJson.get("openid");
        System.err.println(openid1);
        return "redirect:http://127.0.0.1:8080/tabbar/"+bis.getOpenid();
    }
}
